import { songDetail, songUrl, lyric } from '@/api/song';
import playerStore from '@/stores/playerStore';
import { getCurrentInstance, reactive } from 'vue';
import { formatLyricTime, formatMilliseconds } from '@/utils/formatter';
import playlistStore from '@/stores/playlistStore';

export function usePlaySong() {
  const player = playerStore();
  const { proxy } = getCurrentInstance();
  const plStore = playlistStore();

  /**
   * 播放歌曲
   * @param { number } id 歌曲ID
   * @param { 'mo' | 'auto' } type 操作类型
   */
  async function _playSong(id, type = 'mo') {
    if (id === undefined) return; // 没有ID直接返回
    if (player.currentSongInfo.id === id) return; // 如果歌曲是当前正在播放的歌曲则直接返回
    const newSongInfo = reactive({
      id: null, // 歌曲 ID
      name: '', // 歌曲名称
      cover: '', // 歌曲封面
      album: '', // 专辑
      singers: [], // 歌手
      duration: '', // 歌曲时长
      url: '', // 歌曲音频 URL
      lyric: [], // 歌词
    });

    const song = (await songDetail(id)).data;
    newSongInfo.id = song.songs[0].id;
    newSongInfo.name = song.songs[0].name;
    newSongInfo.cover = song.songs[0].al.picUrl;
    newSongInfo.album = song.songs[0].al.name;
    newSongInfo.singers = song.songs[0].ar;
    newSongInfo.duration = formatMilliseconds(song.songs[0].dt);

    const url = (await songUrl(id)).data.data[0].url;
    newSongInfo.url = url;

    const songLyric = (await lyric(id)).data.lrc.lyric.split('\n');
    let formatLyric = [];

    if (songLyric instanceof Array) {
      for (let i in songLyric) {
        if (songLyric[i].split(']')[1] === '') {
          continue;
        }
        formatLyric.push({
          schedule: formatLyricTime(
            songLyric[i].split(']')[0].replace('[', '')
          ),
          lyric: songLyric[i].split(']')[1],
        });
      }
    }
    newSongInfo.lyric = formatLyric;
    player.changeSong(newSongInfo);
    player.changePlayStatus(true);
    if (type !== 'auto') {
      plStore.addSongToPlaylist(newSongInfo);
    }
  }
  const playSong = proxy.lodash.throttle(_playSong, 1000);

  // 获取歌曲 URL
  async function getSongUrl(id) {
    const { data } = (await songUrl(id, 'higher')).data;
    return data[0].url;
  }

  return {
    playSong,
    getSongUrl,
  };
}
